package order

import (
	"apiExample/auth"
	"apiExample/common"
	"errors"
	"fmt"
)

type exportSaleOrderRequest struct {
	Start int32 `json:"start,omitempty"`
	Count int32 `json:"count,omitempty"`
}

type OrderProduct struct {
	ProductId int64 `json:"product_id"`
	Version int32 `json:"version"`
	Price int64 `json:"price"`
	Discount float64 `json:"discount"`
	SellCount int32 `json:"sell_count"`
	SellMoney int32 `json:"sell_money"`
	StockStatus int32 `json:"stock_status"`
}
//自定义字段
type CustomProps struct {
	PropId int32 `json:"prop_id"`
	PropValueType int32 `json:"prop_value_type"`
	PropName string `json:"prop_name"`
	PropValue string `json:"prop_value"`
}

type SaleOrder struct {
	OrderId int64 `json:"order_id"`
	Version int32 `json:"version"`
	Snumber string `json:"snumber"`
	Price int64 `json:"price"`
	CreateTime int64 `json:"create_time"`
	OrderedTime int64 `json:"ordered_time"`
	CreatePid int64 `json:"create_pid"`
	OwnerPid int64 `json:"owner_pid"`
	Status int32 `json:"status"`
	CustomerId int64 `json:"customer_id"`
	Products []*OrderProduct `json:"products"`
	CustomProps []*CustomProps `json:"custom_props"`

}

type exportSaleOrderResult struct {
	Result int32 `json:"result"`
	Errmsg string `json:"errmsg"`
	End bool `json:"end"`
	SaleOrders []*SaleOrder `json:"saleorders"`
}

func ExportSaleOrder(start, count int32) ([]*SaleOrder, error) {
	token, err := auth.GetAccessToken()
	if err != nil {
		return  nil, err
	}

	url := fmt.Sprintf("%s/cgi-bin/saleorder/export?access_token=%s", common.ApiUrl, token)

	req := &exportSaleOrderRequest{
		Start: start,
		Count: count,
	}

	rsp := &exportSaleOrderResult{}
	if err := common.HttpPostData(url, req ,rsp); err != nil {
		return nil, err
	}

	if rsp.Result != 0 {
		return  nil, errors.New(fmt.Sprintf("Server respone not ok, result=%v,msg=%s", rsp.Result, rsp.Errmsg))
	}
	return rsp.SaleOrders, nil
}